<script setup lang="ts">
import { useRouter } from 'vue-router';
import { type DataTableRowKey, NButton, NDropdown } from 'naive-ui';
import { InventoryGoods } from '@/service/api/inventory';
import { useAuthStore } from '@/store/modules/auth';
import SvgIcon from '@/components/custom/svg-icon.vue';

interface Props {
  selectedKeys: DataTableRowKey[];
}

interface Emits {
  (e: 'add'): void;
  (e: 'batch-success'): void;
  (e: 'reset-column-widths'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();
const router = useRouter();

const handleAdd = () => {
  emit('add');
};

const handleBatchDropdown = (key: string) => {
  handleBatchAction(key, props.selectedKeys);
};

const handleBatchAction = async (key: string, selectedRowKeys: (string | number)[]) => {
  if (selectedRowKeys.length === 0) {
    window.$message?.error('请选择商品');
    return;
  }

  // 前端权限检查
  const authStore = useAuthStore();
  const rights = authStore.getInventoryRights();

  const selectedIds = selectedRowKeys as string[];

  // 参考原网页端，限制批量删除数量
  if (key === 'delete' && selectedIds.length > 20) {
    window.$message?.error('最多一次删除20个商品');
    return;
  }

  switch (key) {
    case 'delete':
      if (!rights?.good?.remove) {
        window.$message?.error('暂无删除权限');
        return;
      }

      if (window.confirm(`确定删除选中的 ${selectedIds.length} 个商品吗？`)) {
        // 显示loading提示
        const loadingMessage = window.$message?.loading(`正在批量删除 ${selectedIds.length} 个商品...`, {
          duration: 0
        });

        const response = await InventoryGoods.batchDeleteGoods(selectedIds);

        // 关闭loading提示
        loadingMessage?.destroy();

        if (response && !response.error) {
          window.$message?.success(`成功删除 ${selectedIds.length} 个商品`);
          emit('batch-success');
        } else {
          window.$message?.error('删除失败');
        }
      }
      break;

    case 'sticker':
      if (!rights?.good?.modify) return window.$message?.error('暂无修改权限');

      if (window.confirm(`确定置顶选中的 ${selectedIds.length} 个商品吗？`)) {
        // 显示loading提示
        const loadingMessage = window.$message?.loading(`正在批量置顶 ${selectedIds.length} 个商品...`, {
          duration: 0
        });

        const response = await InventoryGoods.stickerGood(selectedIds);

        // 关闭loading提示
        loadingMessage?.destroy();

        if (response && !response.error) {
          window.$message?.success(`成功置顶 ${selectedIds.length} 个商品`);
          emit('batch-success');
        } else {
          window.$message?.error('置顶失败');
        }
      }
      break;

    case 'edit':
      if (!rights?.good?.modify) return window.$message?.error('暂无修改权限');
      
      // 使用全局H5Router打开批量编辑页面
      window.$h5Router.openGoodBatchEdit(selectedIds, {
        onSuccess: () => {
          window.$message?.success(`成功编辑 ${selectedIds.length} 个商品`);
          emit('batch-success');
        },
        onClose: (hasChanges) => {
          // 如果有变更，刷新列表
          if (hasChanges) {
            emit('batch-success');
          }
        }
      });
      break;
  }
};

const handleImportExport = (key: string) => {
  if (key === 'exportIn') {
    // 导航到商品导入页面 - 修正为正确的路由路径
    router.push('/manage/good/goodexport');
  } else if (key === 'exportOut') {
    handleExportGoods();
  }
};

// 处理商品导出功能 - 参照原项目实现
const handleExportGoods = () => {
  // 权限检查 - 只要能看商品列表就能导出
  const authStore = useAuthStore();
  const rights = authStore.getInventoryRights();
  if (!rights?.good?.see) {
    window.$message?.error('暂无导出权限');
    return;
  }

  // 显示导出选项对话框 - 简化版本
  window.$dialog?.create({
    title: '导出商品信息',
    content: '请选择导出方式',
    positiveText: '不带商品图',
    negativeText: '带商品图片',
    showIcon: false,
    onPositiveClick: () => {
      exportWithoutImages();
    },
    onNegativeClick: () => {
      exportWithImages();
    }
  });
};

// 导出商品（不带图片）
const exportWithoutImages = async () => {
  const loadingMessage = window.$message?.loading('导出中...', { duration: 0 });
  
  try {
    // 获取当前筛选参数，与商品列表保持一致
    const currentFilters = getCurrentFilters();
    const response = await InventoryGoods.exportGoods(currentFilters);
    
    loadingMessage?.destroy();
    
    if (response && !response.error && response.data) {
      // 打开下载链接
      window.open(response.data.data);
      window.$message?.success('导出成功');
    } else {
      window.$message?.error('导出失败');
    }
  } catch (error) {
    loadingMessage?.destroy();
    window.$message?.error('导出失败');
  }
};

// 导出商品（带图片）
const exportWithImages = async () => {
  const loadingMessage = window.$message?.loading('导出中...', { duration: 0 });
  
  try {
    const currentFilters = getCurrentFilters();
    const response = await InventoryGoods.exportGoodsWithImage(currentFilters);
    
    loadingMessage?.destroy();
    
    if (response && !response.error && response.data) {
      window.open(response.data.data);
      window.$message?.success('导出成功');
    } else {
      window.$message?.error('导出失败');
    }
  } catch (error) {
    loadingMessage?.destroy();
    window.$message?.error('导出失败');
  }
};

// 获取当前筛选参数 - 需要从父组件传递或通过事件获取
const getCurrentFilters = () => {
  // 这里需要获取当前商品列表的筛选参数
  // 可以通过props传递或者emit事件从父组件获取
  return {
    // 基本筛选参数，实际应该从父组件获取
    pageNum: 1,
    pageSize: 1000, // 导出时使用大的pageSize确保获取所有数据
    searchText: '',
    brand: '',
    goodsClass: '',
    noReserve: 0,
    productNumber: '',
    order: '-createdAt'
  };
};

const handleResetColumnWidths = () => {
  emit('reset-column-widths');
};

// 暴露给父组件调用的方法
defineExpose({
  handleBatchAction
});
</script>

<template>
  <div class="flex items-center gap-3">
    <NButton type="primary" @click="handleAdd">
      <SvgIcon icon="ant-design:plus-outlined" class="mr-1 h-14px w-14px" />
      添加商品
    </NButton>

    <NDropdown
      :options="[
        { label: '批量删除', key: 'delete' },
        { label: '批量置顶', key: 'sticker' },
        { label: '批量编辑', key: 'edit' }
      ]"
      @select="(key: string) => handleBatchDropdown(key)"
    >
      <NButton>
        <SvgIcon icon="ant-design:setting-outlined" class="mr-1 h-14px w-14px" />
        批量操作
        <SvgIcon icon="ant-design:down-outlined" class="ml-1 h-12px w-12px" />
      </NButton>
    </NDropdown>

    <NDropdown
      :options="[
        { label: '导入商品', key: 'exportIn' },
        { label: '导出商品', key: 'exportOut' }
      ]"
      @select="handleImportExport"
    >
      <NButton>
        <SvgIcon icon="ant-design:import-outlined" class="mr-1 h-14px w-14px" />
        导入导出
        <SvgIcon icon="ant-design:down-outlined" class="ml-1 h-12px w-12px" />
      </NButton>
    </NDropdown>

    <NButton @click="handleResetColumnWidths">
      <SvgIcon icon="ant-design:reload-outlined" class="mr-1 h-14px w-14px" />
      重置列宽
    </NButton>
  </div>
</template>
